package com.portal4kids.controller;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.portal4kids.model.ServicesAdditional;
import com.portal4kids.model.Travel;
import com.portal4kids.util.HibernateUtil;

public class TravelManager extends HibernateUtil{
	
	public Travel save(Travel travel){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		travel.setAvarage(0);
		travel.setNumberOfVotes(0);
		travel.setRating(0);
		travel.setComments("");
		session.save(travel);
		session.getTransaction().commit();
		return travel;
		
	}
	
	public List<Travel> getTravelFromDB(String adress, String attribute){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		List<Travel> travelList = new ArrayList<Travel>();
		if("Dowolna".equals(adress)){
			if("TAK".equals(attribute)){
				Query q = session.createQuery("from Travel where attribute='" + attribute + "'");
				travelList = q.list();
			}else{
				Query q = session.createQuery("from Travel");
				travelList = q.list();
			}
			
		}else{
			if("TAK".equals(attribute)){
				Query q = session.createQuery("from Travel where attribute='" + attribute + "' and adress='" + adress +"'");
				travelList = q.list();
			}else{
				Query q = session.createQuery("from Travel where adress='" + adress +"'");
				travelList = q.list();
			}
			
		}
		
		session.getTransaction().commit();
		return travelList;
		
	}
	
	public List<Travel> getTravelAfterId(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		List<Travel> travelList = new ArrayList<Travel>();
		Query q = session.createQuery("from Travel where id_travel=" + id);
		travelList = q.list();
		session.getTransaction().commit();
		return travelList;
		
	}
	
	public static void addRankTravel(int id, int rank){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Travel travel = (Travel) session.load(Travel.class, id);
		
		int numberOfVotes = travel.getNumberOfVotes();
		numberOfVotes++;
		travel.setNumberOfVotes(numberOfVotes);
		
		int currentRank = travel.getRating();
		currentRank += rank;
		travel.setRating(currentRank);
		if(numberOfVotes == 0){
			System.out.println("0000000000000000000000");
		}else{
		int avarage = currentRank / numberOfVotes;
		travel.setAvarage(avarage);
		}
		session.update(travel);
		session.getTransaction().commit();

	}

}
